package onetotwenty;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import java.util.HashMap;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;

//TODO : 동적 프로그래밍 이용하여 풀어보기
public class ProblemFourteen {
	private Map<Long, Integer> map = new HashMap<Long, Integer>();
	
	@Before
	public void init() {
		long item = 2;
		int n = 1;

		while(item < Integer.MAX_VALUE) {
			map.put(item, n);
			item *= 2;
			n++;
		}
	}

	private int hailstone(long n) {
		int item = 1;

		while (true) {
			Integer value = get(n);

			if(value != null) {
				item += value;
				break;
			}else {
				if(n % 2 == 0) {
					n /= 2;
				} else {
					n = 3 * n + 1;
				}
				item++;
			}
		}
		
		return item;
	}

	private Integer get(long n) {
		if(n <= 0) {
			throw new RuntimeException("" + n);
		}
		
		return map.get(n);
	}

	@Test
	public void testHailstone() {
		assertThat(hailstone(13), is(10));
		assertThat(hailstone(16), is(5));
	}

	@Test
	public void answer() {
		int halistone = 1;
		int value = 1;
		int t = 0;
		for (int i = 1; i <= 1000000; i++) {
			t = hailstone(i);
			if(halistone < t) {
				value = i;
				halistone = t;
			}
		}

		assertThat(value, is(837799));
	}
}